<?php


namespace app\common\model;


use think\Model;

class Vcode extends Model
{
    /**
     * 发送验证码
     * $telephone
     * $type 1用户注册 2 骑手注册 3修改手机号 4 忘记密码
     * @param string $telephone 手机号
     * @return boolean
     */
    public function sendCode($telephone,$type=1){
        if(!checkTelFormat($telephone)) return false;
        $vcode = rand(100000,999999);
//        $vcode = 123456;
        if($type==1) {
            $codeType = config("USER_REGISTER");
        }elseif ($type==2){
            $codeType = config("RIDEE_REGISTER");
        }elseif ($type==3){
            $codeType = config("EDIT_TELEPHONE");
        }elseif ($type==4){
            $codeType = config("FORGET_TELEPHONE");
        }
        $sendResult = sendSms($telephone,$codeType,["code"=>$vcode]);
        $time = time();
        if(!$sendResult["result"]) return false;
        $where = [
            "telephone"=>$telephone,
            "vcode"=>$vcode,
            "send_time"=>$time,
            "lapse_time"=>$time+(config('ALI_VCODE.vcode_time')*60)
        ];
        $insert = $this->insert($where);
        if(!$insert) return false;
        return true;
    }

    /**
     * @param $telephone 手机号
     * @param $code 验证码
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function checkCode($telephone,$code){
        $result["result"] = true;
        $where = [
            "telephone"=>$telephone,
            "vcode"=>$code,
            "lapse_time"=>["egt",time()],
            "is_usable"=>1
        ];
        $find = $this->where($where)->order("vcode_id desc")->find();
        if(!$find) {
            $result["result"] = false;
            $result["msg"] = "验证码已失效,请重新发送";
            return $result;
        }
        $this->save(["is_usable"=>2],["vcode_id"=>$find["vcode_id"]]);
        return $result;
    }

}